import nats, { Message, Stan } from "node-nats-streaming";
import { randomBytes } from "crypto";
import { TicketCreatedListener } from "./events/ticket-created-listener";

const stan = nats.connect('ticketing', randomBytes(4).toString('hex'), {
	url: "http://localhost:4222"
});

/*
stan.on(`connect`, () => {
	console.log("listener 连接到 NATS");

	stan.on(`close`, () => {
		console.log("NATS 关闭!!!");
		process.exit();
	});

	const options = stan
	.subscriptionOptions()
	.setManualAckMode(true)
	.setDeliverAllAvailable()
	.setDurableName("accounting-service");
	const subscription = stan.subscribe(`ticket:created`, `queue-group-name`,options);
	subscription.on(`message`, (msg: Message) => {
		const data = msg.getData();
		if (typeof data === 'string') {
			console.log(`消息编号: ${msg.getSequence()};消息: ${data}`);
		}
		msg.ack();
	});
});

*/


stan.on(`connect`, () => {
	console.log("连接到NATS服务");
	stan.on(`close`, () => {
		console.log("NATS服务关闭");
		process.exit();
	});
	new TicketCreatedListener(stan).listen();
});

process.on(`SIGINT`, () => stan.close());
process.on(`SIGTERM`, () => stan.close());

